#!/usr/bin/perl -w
#
# This script will generate all manual pages
# in the current directory. It is recommeded that
# you run it from the man/man1 subdirectory under
# your GROMACS source tree. The manual pages will
# be installed by the "make install" command.

$bindir = shift || die("Error: provide the binary directory as first argument.");
$ptxt  = shift || die("give me the location of the programs.txt file");

printf "Generating unix manual for GROMACS programs\n";
printf "Man pages will be written in the current dir.\n";
printf "-------------------------------------------\n";

$mam = "Makefile.am";
open(MAM,">$mam") || die("Opening $mam for writing");
printf(MAM "# This file has been generated by mknroff.pl. Don't edit it.\n");
printf(MAM "man_MANS = ");

$dir = `pwd`;
chomp $dir;

@exclude = ( "my_dssp", "copyrgt", "addquote", "GMXRC", "completion.csh",
	     "completion.zsh", "average", "completion.bash", "luck", 
	     "xplor2gmx.pl", "mptest", "ffscan", "demux.pl", "gentop", "mkyaw",
	     "tune_dip", "tune_pol", "hrefify", "options", "genvsites",
	     "pdtest", "bastat", "ehole", "GMXRC.bash", "GMXRC.csh",
             "GMXRC.zsh" );

%desc = ();
open(PPP,"$ptxt") || die("Can't open $ptxt");
$npp = 0;
while($line = <PPP>) {
  if ((index($line,"\|") > 0) && (index($line,"HEAD") < 0)) {
    $line =~ s/ -/ \\-/g;
    @tmp = split('\|',$line);
    if ($#tmp == 1) {
      if (!defined $desc{$tmp[0]}) {
	$desc{$tmp[0]} = $tmp[1];
	$npp++;
      }
      else {
	printf("Multiple entries for $tmp[0] in $ptxt\n");
      }
    }
  }
}
printf("npp = $npp\n");
close PPP;
	     
chdir $bindir;
@PROGRAMS = glob("[a-z]*");
chdir $dir;

$prev = "";
foreach $program ( @PROGRAMS ) {
  $cont = 1;
  foreach $exc ( @exclude ) {
    if ( $exc eq $program )  {
      $cont = 0;
    }
  }
  # Kick out the double precision variants 
  if ($program ne "${prev}_d" ) {
    if ($cont && ( -x "$bindir/$program" )) {
      printf " $program";
      system("$bindir/$program -quiet -man nroff >& /dev/null");
      $pn = "${program}.nroff";
      $p1 = "${program}.1";
      if ( -f $pn) {
	open(PN,"$pn") || die("Opening $pn");
	open(P1,">$p1") || die("Opening $p1 for writing");
	while($line = <PN>) {
	  chomp $line;
	  if ($line eq $program) {
	    if (defined $desc{$program}) {
	      printf("\n");
	      printf(P1 "$program - $desc{$program}\n");
	    }
	    else {
	      printf (" - please add description in $ptxt\n");
	      printf (P1 "$program\n");
	    }
	  }
	  else {
	    printf(P1 "%s\n",$line);
	  }
	}
	close PN;
	close P1;
	unlink $pn;
	printf(MAM "  \\\n\t$p1");
      }
    }
  }
  $prev = $program;
}
printf(MAM "\n\nEXTRA_DIST = \${man_MANS}\n\n");
close MAM;
printf("\n");

